package com.sakura.flowers.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.sakura.flowers.entity.Category;
import com.sakura.flowers.entity.Flower;
import com.sakura.flowers.entity.User;
import com.sakura.flowers.service.CategoryService;
import com.sakura.flowers.service.FlowerService;
import com.sakura.flowers.service.UserService;
import com.sakura.flowers.util.R;
import com.sakura.flowers.vo.CategoryFlowerVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (flower)表控制层
 *
 * @author Sakura
 * @since 2023-11-26 17:08:39
 */
@Api(value = "/api/flower", tags = {"(flower)表控制层"})
@RestController
@RequestMapping("/api/flower")
@CrossOrigin
public class FlowerController {
    /**
     * 服务对象
     */
    @Resource
    private FlowerService flowerService;
    @Resource
    private CategoryService categoryService;
    @Autowired
    private UserService userService;


    /**
     * 分页查询
     *
     * @param pageNo    当前页
     * @param pageSize  数据大小
     * @param searchKey 查询参数
     * @return 查询结果
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "int", name = "pageNo", value = "当前页", required = true),
            @ApiImplicitParam(paramType = "path", dataType = "int", name = "pageSize", value = "数据大小", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "string", name = "searchKey", value = "查询参数")
    })
    @ApiOperation(value = "分页查询", notes = "分页查询", httpMethod = "GET")
    @GetMapping("/list/{pageNo}/{pageSize}/{userId}")
    public R queryByPage(@PathVariable Integer pageNo,
                         @PathVariable Integer pageSize,
                         @PathVariable Long userId,
                         @RequestParam(required = false) String searchKey) {
        LambdaQueryWrapper<Flower> flowerQueryWrapper = new LambdaQueryWrapper<>();
        User user = userService.getById(userId);
        if (user.getAccess() != 2) {
            flowerQueryWrapper.eq(Flower::getFlorist, userId);
        }
        flowerQueryWrapper.like(searchKey != null && searchKey != "", Flower::getName, searchKey);
        Page<Flower> page = flowerService.page(new Page<>(pageNo, pageSize), flowerQueryWrapper);
        return R.success(page);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "主键", required = true)
    })
    @ApiOperation(value = "通过主键查询单条数据", notes = "通过主键查询单条数据", httpMethod = "GET")
    @GetMapping("{id}")
    public R<Flower> queryById(@PathVariable("id") Long id) {
        return R.success(this.flowerService.getById(id));
    }

    @GetMapping("/getByCategory/{id}")
    public R getByCategory(@PathVariable("id") Long id) {
        LambdaQueryWrapper<Flower> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Flower::getCategoryId, id);
        List<Flower> flowerList = flowerService.list(wrapper);
        return R.success(flowerList);
    }

    /**
     * 新增数据
     *
     * @param flower 实体
     * @return 新增结果
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataType = "flower", name = "flower", value = "实体", required = true)
    })
    @ApiOperation(value = "新增数据", notes = "新增数据", httpMethod = "POST")
    @PostMapping
    public R add(@RequestBody Flower flower) {
        boolean result = this.flowerService.save(flower);
        if (!result) {
            return R.error("添加失败");
        }
        return R.success("添加成功");
    }

    /**
     * 编辑数据
     *
     * @param flower 实体
     * @return 编辑结果
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", dataType = "flower", name = "flower", value = "实体", required = true)
    })
    @ApiOperation(value = "编辑数据", notes = "编辑数据", httpMethod = "PUT")
    @PutMapping
    public R edit(@RequestBody Flower flower) {
        boolean result = this.flowerService.updateById(flower);
        if (!result) {
            return R.error("修改失败");
        }
        return R.success("修改成功");
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "主键", required = true)
    })
    @ApiOperation(value = "删除数据", notes = "删除数据", httpMethod = "DELETE")
    @DeleteMapping("/{id}")
    public R deleteById(@PathVariable Long id) {
        boolean result = this.flowerService.removeById(id);
        if (!result) {
            return R.error("删除失败");
        }
        return R.success("删除成功");
    }

    @GetMapping("/select/list")
    public R getSelectList() {
        return R.success(flowerService.list());
    }

    @ApiOperation(value = "添加或者修改", notes = "添加或者修改")
    @Transactional
    @PostMapping("/addOrUpdate")
    public R addOrUpdate(@RequestBody Flower flower) {
        flower.setUpdateTime(new Date());
        //添加
        if (flower.getId() == null || flower.getId() == 0) {
            flower.setCreateTime(new Date());
            boolean save = this.flowerService.save(flower);
            if (!save) {
                return R.error("添加失败，请重新尝试");
            }
            return R.success("添加成功");
        }
        //修改
        boolean update = this.flowerService.updateById(flower);
        if (!update) {
            return R.error("修改失败，请重新尝试");
        }
        return R.success("修改成功");
    }

    /**
     * 获取所有分类的所有药品
     * @return R
     * @author Sakura
     * @date 2023/12/1 21:22
     */
    @ApiOperation(value = "获取所有分类的所有药品", notes = "获取所有分类的所有药品")
    @GetMapping("/group/flower")
    public R groupMedicine() {
        List<Flower> medicineList = flowerService.list();
        Map<Long, List<Flower>> collect = medicineList.stream().collect(Collectors.groupingBy(Flower::getCategoryId));
        List<CategoryFlowerVO> voList = new ArrayList<>();
        for (Map.Entry<Long, List<Flower>> listEntry : collect.entrySet()) {
            Long key = listEntry.getKey();
            Category category = categoryService.getById(key);
            CategoryFlowerVO vo = new CategoryFlowerVO();
            BeanUtils.copyProperties(category, vo);
            vo.setFlowers(listEntry.getValue());
            voList.add(vo);
        }
        return R.success(voList);
    }


    @ApiOperation(value = "获取搜索相关药品", notes = "获取搜索相关药品")
    @GetMapping("/search/{value}")
    public R getSearchGoods(@PathVariable String value) {
        LambdaQueryWrapper<Flower> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(value),Flower::getName,value).or().like(!StringUtils.isEmpty(value),Flower::getContent,value);
        List<Flower> list = flowerService.list(queryWrapper);
        return R.success(list);
    }
}
